import { ReactNode, useRef, useEffect } from 'react';
import { useLocation } from '@remix-run/react';

interface CacheItem {
  component: ReactNode;
  scrollPosition: { x: number; y: number };
}

const cache = new Map<string, CacheItem>();

export function KeepAlive({ children }: { children: ReactNode }) {
  const location = useLocation();
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const key = location.pathname;
    const scrollPosition = {
      x: window.scrollX,
      y: window.scrollY,
    };

    if (!cache.has(key)) {
      cache.set(key, {
        component: children,
        scrollPosition,
      });
    }

    return () => {
      const currentCache = cache.get(key);
      if (currentCache) {
        currentCache.scrollPosition = scrollPosition;
      }
    };
  }, [location.pathname, children]);

  useEffect(() => {
    const cached = cache.get(location.pathname);
    if (cached && containerRef.current) {
      window.scrollTo(cached.scrollPosition.x, cached.scrollPosition.y);
    }
  }, [location.pathname]);

  return <div ref={containerRef}>{children}</div>;
}